<template>
    <van-address-list
        v-model="ChosenAddressId"
        :list="list"
        default-tag-text="默认"
        @add="OnAdd"
        @edit="OnEdit"
        @select="OnSelect"
    />
</template>

<script setup>
const { proxy } = getCurrentInstance();

const business = proxy.$business;

// 选中的地址id
const ChosenAddressId = ref(0);

// 当前登录用户的收货地址数据
const list = ref([]);

const action = ref(proxy.$route.query.action ?? '');

// 生命周期
onBeforeMount(() => GetAddressData());

const GetAddressData = async () =>
{
    const params = {
        busid:business.value.id
    }

    const result = await proxy.$http.post({
        url:'/address/index',
        params
    });

    if(result.code === 1)
    {
        list.value = result.data.map(item => {
            if(item.status == 1)
            {
                ChosenAddressId.value = item.id;
            }

            return {
                id:item.id,
                name:item.consignee,
                tel:item.mobile,
                address:item.provinces.name + item.citys.name + item.districts.name + item.address,
                isDefault:item.status == 1 ? true : false
            }
        })
    }else{
        proxy.$fail(result.msg);
    }
}

const OnAdd = () => proxy.$router.push('/address/add');

const OnEdit = (info) => proxy.$router.push({path:'/address/edit',query:{id:info.id}});

const OnSelect = async (info,index) =>
{
    if(action.value === 'confirm')
    {
        // 从确认订单过来
        proxy.$address.value = {
            id:info.id,
            name:info.name,
            tel:info.tel,
            region_text:info.address
        }
        
        // 返回确认订单
        proxy.$router.back();
    }else{
        // 从收货地址列表
        const result = await proxy.$http.post({
            url:'/address/select',
            params:{
                id:info.id,
                busid:business.value.id
            }
        });

        if(result.code === 1)
        {
            list.value.map(item => item.isDefault = false);

            list.value[index].isDefault = true;
            
            ChosenAddressId.value = list.value[index].id;
        }else{
            proxy.$fail(result.msg);
        }
    }
}

</script>

<style>
.van-address-list{
    height: unset;
    padding: 12px 12px 60px;
}
</style>